package com.yuliang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuliang.constants.SystemConstants;
import com.yuliang.domain.R;
import com.yuliang.domain.dto.AddLinkDto;
import com.yuliang.domain.dto.UpdateLinkDto;
import com.yuliang.domain.entity.Link;
import com.yuliang.domain.vo.LinkVo;
import com.yuliang.domain.vo.PageVo;
import com.yuliang.mapper.LinkMapper;
import com.yuliang.service.LinkService;
import com.yuliang.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 友链(Link)表服务实现类
 *
 * @author makejava
 * @since 2023-09-20 10:00:45
 */
@Service("linkService")
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {

    @Override
    public R getAllLink() {
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Link::getStatus, SystemConstants.LINK_STATUS_NORMAL);
        List<Link> list = list(queryWrapper);
        List<LinkVo> linkVos = BeanCopyUtils.copyBeanList(list, LinkVo.class);
        return R.okResult(linkVos);
    }

    @Override
    public R linkList(Integer pageNum, Integer pageSize, String name, String status) {
        //需要分页查询友链列表 | 能根据友链名称进行模糊查询 | 能根据状态进行查询
        IPage<Link> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(name),Link::getName,name);
        queryWrapper.eq(StringUtils.hasText(status),Link::getStatus,status);

        page(page,queryWrapper);

        List<LinkVo> linkVos = BeanCopyUtils.copyBeanList(page.getRecords(), LinkVo.class);

        return R.okResult(new PageVo(linkVos,page.getTotal()));
    }

    @Override
    public R addLink(AddLinkDto addLinkVo) {
        Link link = BeanCopyUtils.copyBean(addLinkVo, Link.class);
        save(link);
        return R.okResult();
    }

    @Override
    public R getLinkDetail(Long id) {
        Link link = getById(id);
        LinkVo linkVo = BeanCopyUtils.copyBean(link, LinkVo.class);
        return R.okResult(linkVo);
    }

    @Override
    public R updateLink(UpdateLinkDto updateLinkDto) {
        Link link = BeanCopyUtils.copyBean(updateLinkDto, Link.class);
        updateById(link);
        return R.okResult();
    }

    @Override
    public R deleteLink(List<Long> ids) {
        removeByIds(ids);
        return R.okResult();
    }

    @Override
    public R changeLinkStatus(UpdateLinkDto updateLinkDto) {
        Link link = BeanCopyUtils.copyBean(updateLinkDto, Link.class);
        updateById(link);
        return R.okResult();
    }
}
